#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
#include "../ourhdr.h"

#define NLOOPS  1000
#define SIZE    sizeof(long)

static int update(long *);

int main()
{
    int fd,i,counter;
    pid_t pid;
    caddr_t area;
    //if((fd=open("/dev/zero", O_RDWR))<0)
    //{
    //    err_sys("open error");
    //}
    if((area=mmap(0,SIZE,PROT_READ|PROT_WRITE,MAP_ANON|MAP_SHARED,-1,0)) == (caddr_t) -1)
    {
         err_sys("mmap error");
    }
    //close(fd);
    TELL_WAIT();
    if((pid = fork())<0)
    {
        err_sys("fork error");
    }
    else if(pid == 0)
    {
        for(i=1;i<NLOOPS+1; i+=2)
        {
            WAIT_PARENT();
            if((counter=update((long*) area))!=i)
            {
                err_quit("child: expected %d, got %d",i, counter);
            }
            TELL_PARENT(getppid());
        }
    }
    else
    {
        for(i=0;i<NLOOPS;i +=2)
        {
            if((counter = update((long*) area))!=i)
            {
                err_quit("parent: expected %d, got %d", i, counter);
            }
            TELL_CHILD(pid);
            WAIT_CHILD();
        }
    }
    exit(0);
}

static int update(long *ptr)
{
    return((*ptr)++);
}